package admin

import (
	"beego/models"
	"beego/models/admin"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/utils/captcha"
)

type JSONS struct {
	//必须的大写开头
	Code int      `json:"code"`
	Msg  string   `json:"msg"`
	Data []string `json:"data"`
}

type LoginController struct {
	beego.Controller
}

var cpt *captcha.Captcha

func init() {
	// use beego cache system store the captcha data
	store := cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/captcha/", store)
	cpt.ChallengeNums = 4
	cpt.StdWidth = 150
	cpt.StdHeight = 40
}
func (c *LoginController) Get() {
	//c.Ctx.WriteString("admin login")
	c.Data["session_admin_id"] = c.GetSession("admin_id")
	c.TplName = "admin/login/login.html"
}

//执行登录
func (c *LoginController) DoLogin() {
	account := c.GetString("account")
	password := c.GetString("password")
	captcha := cpt.VerifyReq(c.Ctx.Request)
	if !captcha {
		data := &JSONS{-1, "验证码不正确", []string{}}
		c.Data["json"] = data
		c.ServeJSON()
		return
	}
	admin := admin.Admin{}
	models.DB.Where("account = ?", account).First(&admin)
	//fmt.Println(admin)
	if admin.Nickname == "" {
		data := &JSONS{-1, "该账号不存在", []string{}}
		c.Data["json"] = data
		c.ServeJSON()
		return
	}
	//fmt.Println(admin.Password)
	if models.Md5(password) != admin.Password {
		data := &JSONS{-1, "密码不正确", []string{}}
		c.Data["json"] = data
		c.ServeJSON()
		return
	}
	//缓存用户ID
	c.SetSession("admin_id", admin.Id)
	data := &JSONS{200, "正在登录 请稍后~~~", []string{}}
	c.Data["json"] = data
	c.ServeJSON()
	return
}
func (c *LoginController) LoginOut() {
	adminId := c.GetString("admin_id")
	c.DelSession(adminId)
	c.DestroySession()
	data := &JSONS{200, "正在退出，请稍后~~~", []string{}}
	c.Data["json"] = data
	c.ServeJSON()
	return
}
